package org.hank.wanandroid.ui

import android.os.Bundle
import kotlinx.android.synthetic.main.activity_history.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.hank.commom.base.BaseActivity
import org.hank.commom.listener.ReloadListener
import org.hank.wanandroid.R
import org.hank.wanandroid.bean.ArticleBean
import org.hank.wanandroid.listener.OnArticleRecyclerListener
import org.hank.wanandroid.ui.widget.ArticleRecycleWidget
import org.hank.wanandroid.utils.ArticleHistoryUtil

class HistoryActivity : BaseActivity(), OnArticleRecyclerListener, ReloadListener {
    override val layoutResId: Int
        get() = R.layout.activity_history

    var historyList: MutableList<ArticleBean> = ArrayList()

    var articleRecycleWidget = ArticleRecycleWidget(this)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ivBack.setOnClickListener { finish() }
        smartrefresh_history.setOnRefreshListener { onReload() }
        loadingTip.setReloadListener(this)
        var ft = supportFragmentManager.beginTransaction()
        ft.add(R.id.frame_my_history, articleRecycleWidget)
        ft.commit()
    }

    override fun onResume() {
        super.onResume()
        onReload()
    }

    override fun onReload() {
        loadingTip.loading()
        lifecycleSupportedScope.launch(Dispatchers.IO) {
            historyList = ArticleHistoryUtil.getArticleList()
            historyList.sortByDescending { it.readTime }
            if (historyList.isEmpty()) {
                withContext(Dispatchers.Main) {
                    loadingTip.showEmpty()
                    articleRecycleWidget.validateData(null)
                }
            } else {
                withContext(Dispatchers.Main) {
                    loadingTip.dismiss()
                    articleRecycleWidget.notifyReload()
                    articleRecycleWidget.validateData(historyList)
                }
            }
        }
        smartrefresh_history.finishRefresh()
    }

    override fun reload() {
        onReload()
    }
}